document.addEventListener('DOMContentLoaded', async () => {
    try {
        const response = await fetch('/api/hardware');
        const data = await response.json();
        
        // 更新CPU信息
        document.getElementById('cpu-name').textContent = data.cpu.name;
        document.getElementById('cpu-cores').textContent = 
            `${data.cpu.cores}核/${data.cpu.threads}线程`;

        // 更新内存信息
        document.getElementById('memory-total').textContent = `${data.memory.total}GB`;
        document.getElementById('memory-available').textContent = `${data.memory.available}GB`;

        // 更新存储信息
        document.getElementById('storage-total').textContent = `${data.storage.total}GB`;
        document.getElementById('storage-free').textContent = `${data.storage.free}GB`;

        // 生成模型推荐
        const rec = {
            memory_based: {
                '7B': data.memory.total >= 8,
                '13B': data.memory.total >= 16,
                '30B': data.memory.total >= 32,
                '65B': data.memory.total >= 64
            },
            gpu_based: data.gpu?.length > 0 ? {
                '7B-4bit': data.gpu.reduce((sum, g) => sum + parseFloat(g.vram), 0) >= 6,
                '13B-4bit': data.gpu.reduce((sum, g) => sum + parseFloat(g.vram), 0) >= 10,
                '30B-4bit': data.gpu.reduce((sum, g) => sum + parseFloat(g.vram), 0) >= 20,
                '7B-fp16': data.gpu.reduce((sum, g) => sum + parseFloat(g.vram), 0) >= 14
            } : null
        };

        // 渲染推荐结果
        const recContainer = document.getElementById('recommendations');
        const MODEL_CONFIG = {
          '7B': { type: 'cpu', ram: 8, vram: 0, storage: 20 },
          '13B': { type: 'cpu', ram: 16, vram: 0, storage: 40 },
          '30B': { type: 'cpu', ram: 32, vram: 0, storage: 80 },
          '65B': { type: 'cpu', ram: 64, vram: 0, storage: 160 },
          '7B-4bit': { type: 'gpu', ram: 6, vram: 6, storage: 15 },
          '13B-4bit': { type: 'gpu', ram: 10, vram: 10, storage: 30 },
          '30B-4bit': { type: 'gpu', ram: 20, vram: 20, storage: 60 },
          '7B-fp16': { type: 'gpu', ram: 14, vram: 14, storage: 25 }
        };
        
        // 修改推荐结果生成逻辑
        const renderRecommendations = (rec, hwInfo) => {
          return Object.entries(MODEL_CONFIG).map(([model, req]) => {
            const isMemOK = parseFloat(hwInfo.memory.total) >= req.ram;
            const isVramOK = hwInfo.gpu?.length ? hwInfo.gpu.reduce((sum, g) => sum + parseFloat(g.vram || 0), 0) >= req.vram : false;
            const isStorageOK = parseFloat(hwInfo.storage.free) >= req.storage;
            const qualified = (req.type === 'cpu' ? isMemOK : isVramOK) && isStorageOK;
            
            return `<div class="model-card ${qualified ? 'qualified' : 'unqualified'}">
              <div class="model-header">${model}</div>
              <div class="requirements">
                <span>${req.type.toUpperCase()}需求:</span>
                ${req.type === 'gpu' ? `显存≥${req.vram}GB` : `内存≥${req.ram}GB`} 
                · 存储≥${req.storage}GB
              </div>
              <div class="status">${qualified ? '✅ 符合要求' : '❌ 未达标'}</div>
            </div>`;
          }).join('');
        };
        recContainer.innerHTML = renderRecommendations(rec, data);

        if (rec.gpu_based) {
            recContainer.innerHTML += '<h3>GPU加速建议</h3>' + 
                Object.entries(rec.gpu_based)
                    .filter(([, available]) => available)
                    .map(([model]) => `<div class="model-card gpu">${model}</div>`)
                    .join('');
        }

    } catch (error) {
        console.error('获取硬件信息失败:', error);
    }
});

// 在页面加载时自动执行网络测试
const addNetworkTestSection = () => {
  const testContainer = document.createElement('div');
  testContainer.className = 'hardware-section';
  testContainer.innerHTML = `
    <h2>网络连通性测试</h2>
    <button onclick="testPortAccess()">立即测试3000端口</button>
    <div id="port-test-result" class="test-result"></div>
  `;
  document.querySelector('.container').appendChild(testContainer);
};

const testPortAccess = async () => {
  const resultEl = document.getElementById('port-test-result');
  resultEl.innerHTML = '测试中...';
  
  try {
    const response = await fetch('/api/network-test');
    const responseData = await response.json();
    if (responseData.success) {
      const ipList = responseData.localIPs?.map(ip => 
  `<li>${ip.address} (接口: ${ip.interface}, 子网掩码: ${ip.netmask}, 状态: ${ip.status})</li>`
).join('') || '<li>未检测到有效网络接口</li>';
resultEl.innerHTML = responseData.success 
  ? `✅ 端口可用<br>检测到${responseData.localIPs.length}个有效接口：<ul>${ipList}</ul>`
  : `❌ 连接失败：${responseData.message}`;
    } else {
      resultEl.innerHTML = `❌ 连接失败：${responseData.error || '未知错误'}`;
    }
  } catch (e) {
    resultEl.innerHTML = `❌ 网络检测失败：<br>${e.message}<br>${responseData?.message || '请检查网络配置'}`;
  }
};

// 初始化时添加测试区块
addNetworkTestSection();
// 由于当前选中的代码 "});" 本身不完整，推测可能是前面的函数或者代码块没有正确结束或者需要补充内容。
// 但仅根据现有信息难以明确具体修复方式，这里假设是一个函数或代码块结束后需要补充新的内容，以下是一个示例，可根据实际情况调整
// 这里添加一个简单的函数声明作为示例
function someNewFunction() {
  console.log('This is a new function.');
}
// 假设此处需要一个新的函数声明作为示例
function newFunction() {
    console.log('This is a newly added function.');
}
